# -*- coding: utf-8 -*-
"""
NoAccount forms
"""
##
# @author J.Ducastel <nospam0@ducastel.name>

# imports
from django import forms
from models import User, EmailAccount
# from api import get_or_create_user

# exceptions

# classes et fonctions


class EmailAccountRegisterForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField()

    def clean_email(self):
        """
        checks that email is not already used for an(other) account
        """
        try:
            EmailAccount.objects.get(email=self.cleaned_data['email'])
            raise forms.ValidationError('Email already in use')
        except EmailAccount.DoesNotExist:
            return self.cleaned_data['email']

    # @param User
    # @return EmailAccount
    def register(self, user):
        """
        register EmailAccount using current user
        send confirmation email
        return EmailAccount
        """
        if not self.is_valid():
            return False
        return EmailAccount.register(user=user, email=self.cleaned_data['email'], password=self.cleaned_data['password'])

    #class Meta:
    #    model = EmailAccount


class EmailAccountLoginForm(forms.Form):
    """
    email-account login form
    """
    email = forms.EmailField()
    password = forms.CharField()
    UNKNOWN_EMAIL = 'Unkown email'
    BAD_PASSWORD = 'Bad Password'
    # available after validated
    _account = None

    #def clean_email(self):
    #    """searches for account"""
    #    account = self._get_account(self.cleaned_data['email'])
    #    if account:
    #        return self.cleaned_data['email']
    #    else:
    #        raise forms.ValidationError(self.UNKNOWN_EMAIL)

    def clean(self):
        """searches for account, checks password"""
        cleaned_data = self.cleaned_data
        self._account = self._get_account(cleaned_data['email'])
        if self._account:
            # checking password
            if not self._account.check_password(cleaned_data['password']):
                raise forms.ValidationError(self.BAD_PASSWORD)
        else:
            # self._errors['email']
            raise forms.ValidationError(self.UNKNOWN_EMAIL)
        return cleaned_data

    def get_account(self):
        """returns account if validated"""
        return self._account


    def _get_account(self, email):
        """return account if exists"""
        try:
            return EmailAccount.objects.get(email=email)
        except EmailAccount.DoesNotExist:
            return None

#class AdminAccountForm(forms.Form):
#    """to be used oin admin pages, manages both user and account"""
#    email = forms.CharField(blank=True)
#    password = forms.CharField(blank=True)